package com.jiaquyun.jcyx.main.mine

import android.app.Activity.RESULT_OK
import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.jiaquyun.jcyx.R
import com.jiaquyun.jcyx.jetpack.mode.AddressViewModel
import com.module.lemlin.http.Status
import com.module.lemlin.owner.OwnerViewModeFragment
import kotlinx.android.synthetic.main.fragment_address_list.*


class AddressListFragment : OwnerViewModeFragment<AddressViewModel>() {


    companion object {
        const val ACTION_CART_SETTLEMENT = 1
        const val KEY_ADDRESS_ACTION = "KEY_ADDRESS_ACTION"
        fun newInstance(action: Int): AddressListFragment {
            val bundle = Bundle().apply {
                putInt(KEY_ADDRESS_ACTION, action)
            }
            return AddressListFragment().apply {
                arguments = bundle
            }
        }
    }

    private val mAction: Int
        get() = arguments?.getInt(KEY_ADDRESS_ACTION) ?: 0

    private val mAddressListAdapter = AddressListAdapter()

    override fun viewModel(): AddressViewModel {
        return createViewModel(requireActivity())
    }

    override val layoutResId: Int
        get() = R.layout.fragment_address_list

    override fun initView() {

        rvAddressListBody.adapter = mAddressListAdapter.apply {
            setOnItemChildClickListener { _, view, position ->
                if (view.id != R.id.ivAddressListEdit)
                    return@setOnItemChildClickListener
                viewModel.userAddressDetail(getItem(position).id)
            }
            setOnItemClickListener { _, _, position ->
                val itemData = getItem(position)
                if (mAction == ACTION_CART_SETTLEMENT) {
                    val bundle = Bundle().apply {
                        putSerializable(AddressEditFragment.KEY_ADDRESS_EDIT, itemData)
                    }
                    val intent = Intent().apply {
                        putExtras(bundle)
                    }
                    requireActivity().setResult(RESULT_OK, intent)
                    requireActivity().finish()
                } else {
                    viewModel.userAddressDetail(itemData.id)
                }
            }
        }
    }

    override fun onRefreshLoad() {
        viewModel.userAddressList()
    }

    override fun initViewMode() {
        viewModel.addressListLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            val data = response.data?.data
                ?: return@Observer
            mAddressListAdapter.setNewInstance(data)
        })
    }
}

